package com.fdq.dianping.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class AliOss {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    private static EnvironmentVariableCredentialsProvider credentialsProvider;

    static {
        try {
            credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }

    // 填写Bucket名称，例如examplebucket。
    private static String bucketName = "fdqbucket";
    // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
    private static String objectName = "dianping/";

    // 创建OSSClient实例。
    private static OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

    public static String upload(String filename, MultipartFile file) throws IOException {
        String destination = objectName + filename;
        ossClient.putObject(bucketName,destination,file.getInputStream());
        String url = "https://fdqbucket.oss-cn-beijing.aliyuncs.com/dianping/"+filename;
        return url;
    }

    public static String uploadPic(List<MultipartFile> images) {
        List<String> urls = new ArrayList<>();
        images.forEach(image ->{
            // 生成一个随机的UUID
            UUID uuid = UUID.randomUUID();
            // 将UUID转换为字符串
            String uuidString = uuid.toString();
            // 去掉连字符，生成一个纯随机字符串
            String randomString = uuidString.replace("-", "");
            String fileName = randomString+".jpg";
            String destination = objectName + fileName;
            try {
                ossClient.putObject(bucketName,destination,image.getInputStream());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String url = "https://fdqbucket.oss-cn-beijing.aliyuncs.com/dianping/"+fileName;
            urls.add(url);
        });
        // 使用 String.join() 方法连接字符串
        String result = String.join(",", urls);
        return result;
    }



    public AliOss() throws ClientException {
    }
}
